package term

import (
	"context"
	// "fmt"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/blog/model"
	"mall/service/blog/rpc/internal/svc"
	"mall/service/blog/rpc/internal/utils"
	"mall/service/blog/rpc/internal/utils/errorhandler"
	"mall/service/blog/rpc/types/blog"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetTermListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetTermListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetTermListLogic {
	return &BackendGetTermListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetTermListLogic) BackendGetTermList(in *blog.TermListReq) (*blog.TermListResp, error) {
	// logx.Infof("BackendGetTermList : %+v ", in)

	var orderBys []string
	if len(in.OrderBy) > 0 {
		for _, orderBy := range in.OrderBy {
			order := " ASC"
			if orderBy.Order == "1" {
				order = " DESC"
			}
			if orderBy.Field == "id" {
				orderBys = append(orderBys, model.BlogTermColumns.TermID+order)
			}
			if orderBy.Field == "sort" {
				orderBys = append(orderBys, model.BlogTermColumns.Sort+order)
			}
			if orderBy.Field == "count" {
				orderBys = append(orderBys, model.BlogTermColumns.Count+order)
			}
			if orderBy.Field == "createdAt" {
				orderBys = append(orderBys, model.BlogTermColumns.CreatedAt+order)
			}
		}
	}

	var stati string
	var termType string
	if len(in.FilterBy) > 0 {
		for _, filterBy := range in.FilterBy {
			switch filterBy.Field {
			case "status":
				stati = filterBy.In
			case "type":
				termType = filterBy.In
			}
		}
	}

	var page uint64
	var pageSize uint64
	var restricted bool
	var withCount int
	var preCount int64
	filterMap := make(map[string]map[string][]any)
	resp := &blog.TermListResp{}
	if in.Ids != nil && len(*in.Ids) > 0 {
		if vals := modelx.UniqueInterfaces(*in.Ids, 64); len(vals) == 0 {
			return resp, nil
		} else {
			filterMap[model.BlogTermColumns.TermID] = map[string][]any{
				"in": vals,
			}
			restricted = true
			withCount = -1
			preCount = int64(len(vals))
		}
	}

	var statusIsSet bool
	var isAll bool
	statusMap := make(map[string][]any)
	switch termType {
	case "1": // 全部
		// filterMap[model.BlogTermColumns.Status] = map[string][]any{
		// 	"notEqualTo": []any{globalkey.StatusDeleted},
		// }
		statusMap["notEqualTo"] = []any{globalkey.StatusDeleted}
		isAll = true
	case "2": // 正常
		filterMap[model.BlogTermColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusNormal},
		}
		statusIsSet = true
	case "3": // 禁用
		filterMap[model.BlogTermColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusBanned},
		}
		statusIsSet = true
	case "4": // 回收站
		filterMap[model.BlogTermColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusDeleted},
		}
		statusIsSet = true
	}

	if !restricted {
		page = in.Page
		pageSize = in.PageSize
		withCount = 1
	}

	if in.Name != nil && len(strings.TrimSpace(*in.Name)) > 0 {
		filterMap[model.BlogTermColumns.Name] = map[string][]any{
			"contain": {strings.TrimSpace(*in.Name)},
		}
	}
	if in.Slug != nil && len(strings.TrimSpace(*in.Slug)) >= 2 {
		filterMap[model.BlogTermColumns.Slug] = map[string][]any{
			"contain": {strings.TrimSpace(*in.Slug)},
		}
	}
	if in.Taxonomy != nil && len(strings.TrimSpace(*in.Taxonomy)) > 0 {
		taxonomy := utils.ParseTaxonomy(strings.TrimSpace(*in.Taxonomy))
		if taxonomy > 0 {
			filterMap[model.BlogTermColumns.Taxonomy] = map[string][]any{
				"equalTo": {taxonomy},
			}
		}
	}
	if in.ParentId != nil {
		filterMap[model.BlogTermColumns.ParentID] = map[string][]any{
			"equalTo": {*in.ParentId},
		}
	}
	if in.GroupId != nil {
		filterMap[model.BlogTermColumns.TermGroup] = map[string][]any{
			"equalTo": {*in.GroupId},
		}
	}

	var startTimeIn []any
	var endTimeIn []any
	if in.StartTime != nil && len(strings.TrimSpace(*in.StartTime)) > 0 {
		if startTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.StartTime)); err == nil {
			startTimeIn = append(startTimeIn, startTime)
		}
	}
	if in.EndTime != nil && len(strings.TrimSpace(*in.EndTime)) > 0 {
		if endTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.EndTime)); err == nil {
			endTimeIn = append(endTimeIn, endTime)
		}
	}
	createdAtMap := make(map[string][]any)
	if len(startTimeIn) > 0 {
		createdAtMap["moreThanOrEqualTo"] = startTimeIn
	}
	if len(endTimeIn) > 0 {
		createdAtMap["lessThan"] = endTimeIn
	}
	filterMap[model.BlogTermColumns.CreatedAt] = createdAtMap

	var search string
	if in.Search != nil && len(strings.TrimSpace(*in.Search)) > 0 {
		search = strings.TrimSpace(*in.Search)
	}

	// logrus.Info(fmt.Sprintf("BackendGetTermList filterMap: %+v", filterMap))

	if isAll {
		ret, _, err := l.svcCtx.Term.GetList(l.ctx, model.M{
			"search":    search,
			"statistic": "1",
		}, 5, filterMap)
		if err != nil {
			// return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			logx.Errorw("BackendGetTermList GetList statistic err", logx.Field("detail", err.Error()))
		} else if len(ret) > 0 {
			statusStatisticMap := make(map[uint32]uint32)
			var total uint64
			for _, v := range ret {
				statusStatisticMap[uint32(v.Status)] = uint32(v.Count)
				if v.Status != uint8(globalkey.StatusDeleted) {
					total += v.Count
				}
			}
			statusStatisticMap[uint32(4)] = uint32(total)
			resp.StatusStatisticMap = statusStatisticMap
		}
	}

	if !statusIsSet {
		// logrus.Info(fmt.Sprintf("BackendGetTermList in.Status: %+v", in.Status))
		statusIn := modelx.UniqueInterfaces(stati, 32)
		if len(statusIn) > 0 {
			statusMap["in"] = statusIn
		}
		if in.Status != nil {
			statusMap["equalTo"] = []any{*in.Status}
		}
		filterMap[model.BlogTermColumns.Status] = statusMap
	}

	var orderBy string
	if len(orderBys) > 0 {
		orderBy = strings.Join(orderBys, ",")
	}
	var selectCols string
	var simple bool
	if in.SkipContent != nil && *in.SkipContent > 0 {
		simple = true
		selectCols = strings.Join([]string{
			model.BlogTermColumns.TermID,
			model.BlogTermColumns.Name,
			model.BlogTermColumns.Slug,
			model.BlogTermColumns.ParentID,
			model.BlogTermColumns.TermGroup,
		}, ",")
	}
	res, count, err := l.svcCtx.Term.GetList(l.ctx, model.M{
		"page":     page,
		"pageSize": pageSize,
		"search":   search,
		"orderBy":  orderBy,
		"select":   selectCols,
	}, withCount, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if restricted {
		count = preCount
	}
	resp.Total = uint64(count)

	if len(res) > 0 {
		if simple {
			for _, v := range res {
				resp.List = append(resp.List, &blog.TermInfo{
					Id:       &v.TermID,
					Name:     &v.Name,
					Slug:     &v.Slug,
					ParentId: &v.ParentID,
					GroupId:  &v.TermGroup,
				})
			}

			return resp, nil
		}

		var tids []any
		var taxonomy uint16
		for _, v := range res {
			tids = append(tids, v.TermID)
			if taxonomy == 0 {
				taxonomy = v.Taxonomy
			}
		}

		idMetumMap := make(map[uint64][]*model.BlogTermMetum)
		if in.WithMeta != nil && *in.WithMeta > 0 {
			subFilterMap := make(map[string]map[string][]any)
			subFilterMap[model.BlogTermMetumColumns.TermID] = map[string][]any{
				"in": tids,
			}
			subFilterMap[model.BlogTermMetumColumns.MetaKey] = map[string][]any{
				"in": {
					"_thumbnail_id",
					"_thumbnail_url",
				},
			}
			list, _, err := l.svcCtx.Term.GetMeta(l.ctx, model.M{}, -1, subFilterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			if len(list) > 0 {
				for _, v := range list {
					idMetumMap[v.TermID] = append(idMetumMap[v.TermID], v)
				}
			}
		}

		idMediaMap := make(map[uint64][]*blog.TmpMediaInfo)
		if in.WithMedia != nil && *in.WithMedia > 0 {
			subFilterMap := make(map[string]map[string][]any)
			subFilterMap[model.BlogAttachmentRelationshipColumns.ObjectID] = map[string][]any{
				"in": tids,
			}
			subFilterMap[model.BlogAttachmentRelationshipColumns.ObjectType] = map[string][]any{
				"equalTo": {taxonomy + globalkey.PostTypeTermOffset},
			}
			subFilterMap[model.BlogAttachmentRelationshipColumns.AttachmentThumbnail] = map[string][]any{
				"equalTo": {1},
			}
			list, _, err := l.svcCtx.Term.GetMedia(l.ctx, model.M{}, -1, subFilterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			if len(list) > 0 {
				for _, v := range list {
					idMediaMap[v.ObjectID] = append(idMediaMap[v.ObjectID], &blog.TmpMediaInfo{
						Uid:       &v.AttachmentRelationshipID,
						Id:        pointy.GetPointer(strconv.FormatInt(int64(v.AttachmentID), 10)),
						Thumbnail: pointy.GetPointer(uint32(v.AttachmentThumbnail)),
						Order:     pointy.GetPointer(uint32(v.AttachmentOrder)),
						Uri:       &v.AttachmentSource,
						Url:       &v.AttachmentImageURL,
						AltText:   &v.AttachmentImageAlt,
						MetaData:  &v.AttachmentImageMeta,
					})
				}
			}
		}

		for _, v := range res {
			var meta []*blog.MetaInfo
			var media []*blog.TmpMediaInfo
			if ms, ok := idMetumMap[v.TermID]; ok {
				var mediaId *string
				var mediaUrl *string
				for _, m := range ms {
					key := m.MetaKey
					if len(key) > 0 && m.MetaValue.Valid {
						val := m.MetaValue.String
						switch key {
						case "_thumbnail_id":
							mediaId = pointy.GetPointer(val)
						case "_thumbnail_url":
							mediaUrl = pointy.GetPointer(val)
						default:
							meta = append(meta, &blog.MetaInfo{
								Key:   pointy.GetPointer(key),
								Value: pointy.GetPointer(val),
							})
						}
					}
				}
				if mediaUrl != nil {
					media = append(media, &blog.TmpMediaInfo{
						Id:        mediaId,
						Thumbnail: pointy.GetPointer(uint32(1)),
						Url:       mediaUrl,
					})
				}
			}

			if ms, ok := idMediaMap[v.TermID]; ok {
				media = ms[:]
			}

			resp.List = append(resp.List, &blog.TermInfo{
				Id:           &v.TermID,
				Name:         &v.Name,
				Slug:         &v.Slug,
				Taxonomy:     pointy.GetPointer(utils.FormatTaxonomy(int32(v.Taxonomy))),
				ParentId:     &v.ParentID,
				GroupId:      &v.TermGroup,
				Count:        pointy.GetPointer(uint32(v.Count)),
				Desc:         &v.Description,
				FilteredDesc: &v.DescriptionFiltered,
				Sort:         pointy.GetPointer(uint32(v.Sort)),
				Status:       pointy.GetPointer(uint32(v.Status)),
				CreatedAt:    pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
				UpdatedAt:    pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
				DeletedAt:    pointy.GetPointer(modelx.FormatNullDotTime(v.DeletedAt, "")),
				Meta:         meta,
				Media:        media,
			})
		}
	}

	return resp, nil
}
